import 'dart:io';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:sports_new/base/base_controller.dart';
import 'package:sports_new/entity/other/image_upload_result_entity.dart';
import 'package:sports_new/server/api/user_api.dart';
import 'package:sports_new/server/http/dio_utils.dart';
import 'package:sports_new/utils/image_utils.dart';
import 'package:sports_new/utils/toast_utils.dart';
import 'package:sports_new/widgets/base/qkd_dialog.dart';

class NewPostLogic extends BaseController {
  final textController = TextEditingController();
  List<String> imageList = [];
  String text = '';

  @override
  void onInit() {
    // textController.addListener(() {
    //   index = controller.index;
    // });
    super.onInit();
  }

  onSubmit() async {
    if (imageList.isEmpty && text.trim().isEmpty) {
      ToastUtils.show('内容不能为空');
      return;
    }
    // if (text.isEmpty) {
    //   ToastUtils.show('内容不能为空');s
    //   return;
    // }
    final result = await UserApi.publishPost(imageList.join(','), text.trim());
    if (result == 200) {
      ToastUtils.show('发帖成功');
      Get.back();
    }
  }

  void addPhotoFromCamera() async {
    final image = await ImageUtils.pickPhotoFromCamera();
    if (image == null) {
      return;
    }

    XFile? compressImage = await ImageUtils.compressImage(image.path);
    String path = compressImage!.path;
    List<ImageUploadResultEntity>? result =
        await DioUtils.uploadImage([path], 'images', width: 1080, height: 1920);

    if (result != null) {
      imageList.add(result.first.url!);
    }
    update();
  }

  void addPhotoFromGallary() async {
    final images =
        await ImageUtils.pickPhotoFromGallery(maxPhotos: 9 - imageList.length);
    if (images == null) {
      return;
    }
    List<XFile> files = [];
    for (var data in images) {
      File? file = await data.file;
      XFile? compressImage = await ImageUtils.compressImage(file!.path);
      if (compressImage != null) {
        files.add(compressImage);
      }
    }
    List<ImageUploadResultEntity>? result = await DioUtils.uploadImage(
        files.map((e) => e.path).toList(), 'images',
        width: 1080, height: 1920);
    if (result != null) {
      imageList.addAll(result.map((e) => e.url!));
      update();
    }
  }

  onDeleteImage(int index) {
    imageList.removeAt(index);
    update();
  }

  onBack() async {
    if (text.isNotEmpty) {
      final result =
          await Get.dialog(QkdDialog.alert('关闭页面会清空已输入内容，是否继续退出？'));
      if (result == true) {
        Get.back();
      }
    } else {
      Get.back();
    }
  }
}
